//
//  HistoryMiddleware.swift
//  hello
//
//  Created by 赵康 on 2024/12/23.
//
import Vapor
import Fluent
	// 首先定义一个 async 版本的 ModelMiddleware 协议
protocol AsyncModelMiddleware {
	func create(model: History, on db: Database, next: AnyModelResponder) async throws -> Void
	func update(model: History, on db: Database, next: AnyModelResponder) async throws -> Void
}
struct HistoryMiddleware: ModelMiddleware {
	let app: Application
	typealias Model = History
	func create(model: History, on db: Database, next: AnyModelResponder) -> EventLoopFuture<Void> {
		return next.create(model, on: db).flatMap { _ in
			Task {
				do {
					try await StatisticsService.handleDatabaseEvent(app: app, history: model)
				} catch {
					app.logger.error("Failed to process statistics: \(error)")
				}
			}
			return db.eventLoop.makeSucceededFuture(())
		}
	}
	func update(model: History, on db: Database, next: AnyModelResponder) -> EventLoopFuture<Void> {
		return next.update(model, on: db).flatMap { _ in
			Task {
				do {
					try await StatisticsService.handleDatabaseEvent(app: app, history: model)
				} catch {
					app.logger.error("Failed to process statistics: \(error)")
				}
			}
			return db.eventLoop.makeSucceededFuture(())
		}
	}
}
